<?php
declare(strict_types=1);
namespace App\Controller\Api\V1\Common;

use App\Controller\Api\BaseController;
use App\Core\Uploader;
use Hyperf\Di\Annotation\Inject;
use Qiniu\Auth;

class FileController extends BaseController{
    /**
     * @Inject
     * @var Uploader
     */
    private $uploader;

    public function upload(){
        $return = $this->uploader->uploadByFile($this->request);
        return $this->response->success($return);
    }

    public function getQiniuToken(){
        $config_qiniu = config('file.storage.qiniu');
        $redis = redis();
        $upload_token = $redis->get('cdd_qiniu_upload_token');
        $upload_token_expire_time = $redis->get('cdd_qiniu.upload_token_expire_time');
        if(!$upload_token || ($upload_token_expire_time && $upload_token_expire_time< time()-600)){
            $auth = new Auth($config_qiniu['accessKey'],$config_qiniu['secretKey']);
            $upToken = $auth->uploadToken($config_qiniu['bucket']);
            $token_arr = explode(':',$upToken);
            $sceret = $token_arr[2];
            $expire = json_decode(base64_decode($sceret));
            $redis->set('cdd_qiniu.upload_token',$upToken);
            $redis->set('cdd_qiniu.upload_token_expire_time',$expire->deadline);
            return $this->response->success([
                'uploadToken' => $upToken,
                'expire_time' => $expire->deadline
            ]);
        }
        return $this->response->success([
            'uploadToken' => $upload_token,
            'expire_time' => $upload_token_expire_time
        ]);
    }
}